#coding=utf-8
'''
# @Name:index_resource
# @author:mysouil
# @Description:index资源
# @DATE:2022/9/27 21:29
# @Modified By:
'''
import json
from flask_restful import Resource,reqparse,request
from comment.models.index import Category,HomeNewProduct,Product,HomeRecommendProduct,CmsSubject,CmsSubjectProductRelation,\
    CmsSubjectCategory
from comment.utils.dataToDict import datalist2dict,data2dict
from comment.utils.shopping_redis import redis_client

class Shopping_Category(Resource):
    def get(self):
        # 从redis中读取数据
        data_cache = redis_client.get('index_category')
        
        # 如果redis中存有数据，则返回redis中的数据
        if data_cache:
            return json.loads(data_cache)
        
        # 如果redis中没有数据，则从mysql中查询数据，并写入redis
        rq = reqparse.RequestParser()
        rq.add_argument('parent_id',required=True,type=int)
        req = rq.parse_args()
        
        parent_id = req.parent_id if req.parent_id else 0
        
        data = self.getData(parent_id)
        if data:
            for item in data:
                item.update({'list': ''})
                data_second = self.getData(item['id'])
                item['list'] = data_second
                
                for item1 in data_second:
                    item1.update({'list': ''})
                    data_third = self.getData(item1['id'])
                    item1['list'] = data_third
                    
            #  写入数据到redis
            redis_client.setex('index_category',3600*24,json.dumps(data))
            return data
        else:
            return {'message':'null'}
            
    @staticmethod
    def getData(parent_id):
        categorys = Category.query.with_entities(Category.id, Category.parent_id, Category.name).filter(
            Category.parent_id == parent_id).order_by(Category.sort.asc()).all()
    
        if categorys:
            return datalist2dict(categorys)
        else:
            return None

# 新品推荐的资源类
class Shopping_HomeNewProduct(Resource):
    
    def get(self):
        new_product = HomeNewProduct.query.join(Product,HomeNewProduct.product_id==Product.id).with_entities(Product.id,
            Product.default_pic,Product.price,Product.product_name,Product.rel_category3_id).order_by(HomeNewProduct.sort.asc())\
                .limit(10).all()
    
        if new_product:
            return datalist2dict(new_product)
        return {'statusCode':'400','message':'null'}
    
# 人气热搜的资源类
class Shopping_HomeRecommendProduct(Resource):
    def get(self):
        data_cache = redis_client.get('index_HomeRecommendProduct')
        if data_cache:
            return json.loads(data_cache)

        recommendProduct = HomeRecommendProduct.query.join(Product,HomeRecommendProduct.product_id==Product.id) \
            .with_entities(Product.id,Product.default_pic,Product.product_name,Product.price,Product.rel_category3_id) \
            .limit(10).all()
        
        if recommendProduct:
            data = datalist2dict(recommendProduct)
            # 将查询到的数据存入redis
            redis_client.setex('index_HomeRecommendProduct',3600*24,json.dumps(data))
            return data
        
        return {'message':'null'}
    

# 首页专题资源类
class Shopping_RecommendSubject(Resource):
    def get(self):
        data_cache = redis_client.get('index_RecommendSubject')
        if data_cache:
            return json.loads(data_cache)
        
        cmsSubject = CmsSubject.query.filter(CmsSubject.show_status==1).all()
        
        if cmsSubject:
            data = datalist2dict(cmsSubject)
            
            for i in range(len(data)):
                cmsProduct = CmsSubjectProductRelation.query.join(Product,CmsSubjectProductRelation.product_id==Product.id)\
                .filter(CmsSubjectProductRelation.subject_id==data[i]['id']).with_entities(Product.id,Product.default_pic,
                Product.price,Product.product_name,Product.rel_category3_id).limit(10).all()
                
                if cmsProduct:
                    data[i]['productList'] = datalist2dict(cmsProduct)
                else:
                    data[i]['productList'] = ''
                    
            # 写入redis
            redis_client.setex('index_RecommendSubject', 3600 * 24, json.dumps(data))
            
            return data
        
        return {'message':'null'}
            